package com.quan.admin.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.quan.admin.entity.SysFile;
import com.quan.admin.service.SysFileService;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.bean.UploadVo;
import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.exception.BizException;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.commons.core.utils.DateUtils;
import com.quan.commons.core.utils.FileUtils;
import com.quan.commons.core.utils.PageUtils;
import com.quan.commons.core.utils.RandomUitl;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 系统-文件表
 *
 * @author yhaoquan
 * @email yhaoquan@163.com
 * @date 2020-08-08 20:15:07
 */
@Slf4j
@Api(tags = "系统-文件表")
@RestController
@RequestMapping("sysfile")
public class SysFileController extends MyBaseController {

    @Autowired
    private SysFileService service;

    @Autowired
    private SystemValueProperties properties;

    /**
     * 自定义分页列表
     * @param entity
     * @return
     */
    @GetMapping(value = "selectMyPage")
    public Object selectMyPage(SysFile entity) {
        IPage<SysFile> page = this.service.selectMyPage(new PageUtils(request), entity);
        return R.ok().put("data", page);
    }

    /**
     * 分页列表
     * @param entity
     * @return
     */
    @GetMapping(value = "page")
    public Object page(SysFile entity) {
        IPage<SysFile> page = this.service.selectPage(new PageUtils(request), entity);
        return R.ok().put("data", page);
    }

    /**
     * 列表
     * @param entity
     * @return
     */
    @GetMapping(value = "list")
    public Object list(SysFile entity) {
        List<SysFile> list = this.service.list(new PageUtils(request), entity);
        return R.ok().put("data", list);
    }


    /**
     * 信息
     * @param {id}
     * @return
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		SysFile sysFile = this.service.getById(id);
        return R.ok().put("data", sysFile);
    }

    /**
     * 保存
     * @param entity
     * @param bindingResult
     * @return
     */
    @PostMapping("save")
    public R save(@Valid @RequestBody SysFile entity, BindingResult bindingResult){
		this.service.save(entity);
        return R.ok();
    }

    /**
     * 修改
     * @param entity
     * @param bindingResult
     * @return
     */
    @PostMapping("update")
    public R update(@Valid @RequestBody SysFile entity, BindingResult bindingResult){
		this.service.updateById(entity);
        return R.ok();
    }

    /**
     * 删除
     * @param params idList: [1,2,3]
     * @return
     */
    @PostMapping("delete")
    public R delete(@RequestBody Map<String, Object> params) {
        if (null != params && !params.isEmpty()) {
            List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
            this.service.removeByIds(idList);
            return R.ok();
        } else {
            return R.failure();
        }
    }

    @PostMapping(value = "/upload")
    public Object upload(UploadVo vo, HttpServletRequest request) {
        try {
            // 文件上传根目录
            String rootPath = this.properties.getUpload() ;

            // 文件上传目录
            String dirPath = null;
            // 文件名称
            String fileName = null;

            // 指定目录或生成日期目录
            if(StringUtils.isNotBlank(vo.getDirPath())) {
                dirPath = vo.getDirPath() + File.separator;
            } else {
                dirPath = File.separator + DateUtils.getDate(DateUtils.YYYYMMDD) + File.separator;
            }

            // 生成日期目录，需同时指定目录
            if(vo.isGenDataFolder() && StringUtils.isNotBlank(vo.getDirPath())) {
                dirPath += DateUtils.getDate(DateUtils.YYYYMMDD) + File.separator;
            }

            // 生成随机文件名称
            if(StringUtils.isNotBlank(vo.getFileName())) {
                fileName = vo.getFileName();
            } else {
                fileName = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSSS) + "_" + RandomUitl.generateInteger(4);
            }

            // 创建目录
            FileUtils.createDir(rootPath + dirPath) ;

            // 获取多媒体请求对象
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

            // 取得MultiValueMap集合
            MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
            Set<Map.Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet();
            for (Map.Entry<String, List<MultipartFile>> entry : entrySet) {

                // 获取MultipartFile集合
                List<MultipartFile> multipartFiles = entry.getValue();
                for (MultipartFile multipartFile : multipartFiles) {
                    // 文件后缀
                    String extension = "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());

                    // 文件存储的相对路径
                    String destPath = FilenameUtils.separatorsToUnix(dirPath + fileName + extension) ;

                    // 文件存储路径
                    String storePath = FilenameUtils.separatorsToUnix(rootPath + destPath);

                    // 保存文件到磁盘
                    multipartFile.transferTo(new File(storePath));

                    SysFile entity = new SysFile();
                    entity.setName(fileName);
                    entity.setSize(multipartFile.getSize());
                    entity.setType(multipartFile.getContentType());
                    entity.setPath(destPath);
                    entity.setHref(vo.getHref());
                    this.service.save(entity);

                    log.info("==>文件上传：{}", storePath);

                    return R.ok("文件上传成功").put("data", entity);
                }
            }
        } catch (Exception e) {
            throw new BizException("文件上传失败");
        }
        return R.failure("文件上传失败");
    }

}
